package business

import (
	"gitee.com/smallow/srpc/infrastructure/conf"
	"gitee.com/smallow/srpc/infrastructure/model"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"time"
)

// 查找公司  返回公司视图(包括公司及账户信息)及部门信息
func FindCompany(where *model.CompanyView) (*model.CompanyView, error) {
	company := &model.CompanyView{}
	err := conf.GetMysqlDB().Table("v_company").Where(where).Find(company).Error
	return company, err
}

// 查找公司下部门
func FindDep(where *model.Department) (*[]model.Department, error) {
	department := &[]model.Department{}
	err := conf.GetMysqlDB().Where(model.Department{CompanyID: where.CompanyID}).Find(department).Error
	return department, err
}

// 根据公司名查找公司
func FindCompanyBy(where *model.Company) *model.Company {
	company := &model.Company{}
	conf.GetMysqlDB().Where(where).First(company)
	return company
}

// 根据公司id查询公司信息 返回公司信息及部门信息
func FindCompanyByID(where *model.Company) (*model.Company, error) {
	company := &model.Company{}
	conf.GetMysqlDB().Where(where).Find(company)
	department := &[]model.Department{}
	err := conf.GetMysqlDB().Where(model.Department{ParentID: 0, CompanyID: where.ID}).Find(department).Error
	return company, err
}

// 保存公司信息
func SaveCompany(company *model.Company) error {
	if company.ID != 0 {
		t := time.Now().Format("2006-01-02 15:04:05")
		return conf.GetMysqlDB().Table((&model.Company{}).TableName()).Where("id=? and app_id=?", company.ID, company.AppID).Updates(map[string]interface{}{
			"name":           company.Name,
			"short_name":     company.ShortName,
			"contact_person": company.ContactPerson,
			"contact_phone":  company.ContactPhone,
			"company_type":   company.CompanyType,
			"address":        company.Address,
			"state":          company.State,
			"auth_state":     company.AuthState,
			"update_at":t,
		}).Error
	} else {
		return conf.GetMysqlDB().Create(company).Error
	}
}

// 账户主体是否已存在账户
func ExistAccount(where *model.Account) bool {
	var temp model.Account
	conf.GetMysqlDB().Where(where).Find(&temp)
	if temp.ID != 0 {
		return true
	} else {
		return false
	}
}

// 账户绑定手机号是否已存在
func ExistPhone(phone string) bool {
	if phone == "" {
		return false
	}
	var temp model.Account
	conf.GetMysqlDB().Where(model.Account{BindPhone: phone}).Find(&temp)
	if temp.ID != 0 {
		return true
	} else {
		return false
	}
}

// 创建账号
func CreateAccountInfo(account *model.Account, roleId int) error {
	err := conf.GetMysqlDB().Transaction(func(tx *gorm.DB) error {
		// 1. 创建账号
		err := tx.Create(account).Error
		if err != nil {
			return err
		}
		// 2. 分角色
		err = tx.Table("is_account_role").Create(map[string]interface{}{"account_id": account.ID, "role_id": roleId, "app_id": account.AppID}).Error
		if err != nil {
			return err
		}
		return nil
	})
	return err
}

// 删除公司  会删除公司下部门 员工 及公司账号，部门账号，员工账号
func DeleteCompany(where *model.Company) error {
	err := conf.GetMysqlDB().Transaction(func(tx *gorm.DB) error {
		// 删公司
		err1 := tx.Where("id = ? and app_id=?", where.ID, where.AppID).Delete(&model.Company{}).Error
		if err1 != nil {
			return err1
		}
		// 删除公司账号
		err2 := tx.Where("body_id = ? and body_type=1 and app_id=?", where.ID, where.AppID).Delete(&model.Account{}).Error
		if err2 != nil {
			return err2
		}
		t := time.Now().Format("2006-01-02 15:04:05")
		param := []interface{}{
			t, t, where.ID, where.AppID,
		}
		// 删部门账号
		err3 := tx.Exec("UPDATE is_department a  LEFT JOIN is_account b on a.id=b.body_id SET b.delete_at=? WHERE company_id =? AND body_type=3 AND a.app_id=?", param...).Error
		if err3 != nil {
			return err3
		}
		// 删部门
		err4 := tx.Where("company_id = ? and  app_id=?", where.ID, where.AppID).Delete(&model.Department{}).Error
		if err4 != nil {
			return err4
		}
		// 删人员账号
		err5 := tx.Exec("UPDATE is_employee a  LEFT JOIN is_account b on a.id=b.body_id SET b.delete_at=? WHERE company_id =? AND body_type=2 AND a.app_id=?", param...).Error
		if err5 != nil {
			return err5
		}
		// 删人
		err6 := tx.Where("company_id = ? and  app_id=?", where.ID, where.AppID).Delete(&model.Employee{}).Error
		if err6 != nil {
			return err6
		}
		return nil
	})
	return err
}

/**
更新公司账号
*/
func UpdatesCompanyAccountInfo(account *model.Account) error {
	if account.BodyID == 0 {
		return errors.New("账号主体标识为空!")
	}
	if account.BodyType == 0 {
		return errors.New("账号主体类型为空!")
	}
	if account.ID != 0 {
		return conf.GetMysqlDB().Updates(account).Error
	} else {
		return conf.GetMysqlDB().Create(account).Error
	}
}
